<template>
  <el-input
    v-model="searchInput"
    clearable
    placeholder="拼音码、项目名称检索:"
    style="width: 480px"
    @input="searchInputChange"
  >
    <template #append><span style="color: #0d30e8">点击项目中下拉框，可以取消勾选多余的部位信息</span></template>
  </el-input>
  <div class="mb10 mt10" style="border-bottom: 1px dashed #9c9c9c"/>
  <el-scrollbar height="500px">
    <div>
      <el-text v-for="(item, index) in examTypeList">
        <el-text class="exam-type-div fz17"
        >{{ item.name }}
          <el-text>
            <el-checkbox-group v-model="examClinicCheckList">
              <template v-for="(clinicInfo, index) in item.examVsClinicVoList">
                <el-checkbox
                  v-if="clinicInfo.isShowType"
                  :key="clinicInfo.vsId"
                  :value="clinicInfo.vsId"
                  class="mb5 exam-lab-check"
                >
                  <div class="fz15 exam-lab-check-div mb5">
                    {{ clinicInfo.itemName }}
                  </div>
                  <span class="exam-lab-type-div fz16" style="bottom: 42px; right: 20px;font-size: 13px">
                    单价
                  </span>
                  <span class="exam-lab-type-div fz16">
                    {{ parseFloat(clinicInfo.totalPrice).toFixed(2) }}元
                  </span>
                  <div style="width: 180px;margin-bottom: 0;margin-left: 5px;">
                    <el-select v-model="clinicInfo.examPositionArray" multiple>
                      <el-option v-for="dict in positionTypeArr"
                                 :key="dict.dictValue"
                                 :label="dict.dictLabel" :value="dict.dictValue"/>
                    </el-select>
                  </div>
                </el-checkbox>
              </template>
            </el-checkbox-group>
          </el-text>
        </el-text>
      </el-text>
    </div>
  </el-scrollbar>
</template>

<script lang="ts" setup>
import {listExamType} from "@/api/base/examType";
import {useDictStoreHook} from "@/store/modules/dict";

const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData("position_type"));

const props = defineProps({
  orgId: {
    type: String,
    default: "",
  },
  examType: {
    type: String,
    default: "",
  },
});

const positionTypeArr = ref<any>([])
// 检索值
const searchInput = ref<String>("");
// 类型数组
const examTypeList = ref<any>();
// 已选项目数组
const examClinicCheckList = ref<any>([]);
// 待选数组 All
let examClinicList: any = [];
function getListExamTypeFun() {
  return new Promise((resolve, _reject) => {
    examClinicList = [];
    const param = {
      orgId: props.orgId,
      parentId: props.examType,
      delFlag: "0",
    };
    listExamType(param).then((res: any) => {
      positionTypeArr.value = dictDataMap.value['position_type']
      examTypeList.value = res.data;
      res.data.forEach((element: any) => {
        element.examVsClinicVoList.forEach((item: any) => {
          item.examType = element.examTypeId
          item.examTypeName = element.name;
          // 设置诊疗项目ID
          item.clinicItemId = item.clinicId;
          item.price = item.totalPrice;
          item.itemType = item.examId;
          item.num = 1;
          // 是否显示项目
          item.isShowType = true;
          examClinicList.push(item);
        });
      });
      // 处理响应
      resolve(examClinicList);
    });
  });

}

// 项目检索
function searchInputChange() {
  examTypeList.value.forEach((typeList: any) => {
    typeList.examVsClinicVoList.forEach((itemList: any) => {
      const itemName = itemList.itemName;
      const inputCode = itemList.inputCode;
      itemList.isShowType = inputCode.toLowerCase().indexOf(searchInput.value.toLowerCase()) > -1 ||
        itemName.indexOf(searchInput.value) > -1;
    });
  });
}

/** 清空检索框 */
function emptySearchInput() {
  searchInput.value = "";
}

/** 清空项目列表 */
function emptyExamTypeList() {
  debugger
  examTypeList.value = [];
}

/**
 * 检查项目选择保存事件
 * 该方法用于处理用户选择检查项目后的保存操作，会验证选中项目是否选择了部位信息，
 * 并将选中项目的部位信息转换为逗号分隔的字符串格式。
 * @returns {Array} 包含选中检查项目信息的数组，如果有项目未选择部位信息则返回空数组
 */
function saveExamDialog(): any {
  // 用于存储最终选中的检查项目对象列表
  let examClinicCheckObjList: any = [];
  // 获取部位类型列表
  const positionTypeList = dictDataMap.value['position_type']
  // 清空检索输入框
  emptySearchInput();
  // 循环遍历已选中的检查项目ID列表
  examClinicCheckList.value.forEach((examClinic: any) => {
    // 查找已选中项目在所有检查项目列表中的索引
    let index = examClinicList.findIndex((item: any) => {
      return examClinic === item.vsId;
    });
    // 如果找到对应的项目，则将其添加到最终选中的项目对象列表中
    if (index > -1) {
      examClinicCheckObjList.push(examClinicList[index]);
    }
  });
  // 遍历最终选中的项目对象列表
  for (let i = 0; i < examClinicCheckObjList.length; i++) {
    // 检查当前项目是否选择了部位信息
    if (examClinicCheckObjList[i].examPositionArray.length <= 0) {
      // 如果未选择部位信息，给出错误提示并返回空数组
      ElMessage.error(`勾选的检查项目【${examClinicCheckObjList[i].itemName}】没有选择【部位】信息，不能开单`)
      return [];
    }
    // 用于存储当前项目有效的部位信息
    const thisList: any = []
    // 遍历当前项目已选择的部位信息
    examClinicCheckObjList[i].examPositionArray.forEach((examPositionDict: any) => {
      // 查找已选择的部位信息在部位类型列表中的索引
      let index = positionTypeList.findIndex((item) => {
        return examPositionDict === item.dictValue
      })
      // 如果找到对应的部位信息，则将其添加到有效部位信息列表中
      if (index > -1) {
        examClinicCheckObjList[i].examPositionArray = []
        thisList.push({
          dictValue: positionTypeList[index].dictValue,
          dictLabel: positionTypeList[index].dictLabel
        })
      }
    })
    // 更新当前项目的部位信息为有效部位信息列表
    examClinicCheckObjList[i].examPositionArray = thisList
    // 将有效部位信息列表中的 dictValue 转换为逗号分隔的字符串，并赋值给 examPosition 属性
    examClinicCheckObjList[i].examPosition = thisList.map((item: any) => item.dictValue).join(',');
  }
  // 返回包含选中检查项目信息的数组
  return examClinicCheckObjList;
}

/**
 * 从父页面form中点击后获取数据
 * @param row
 */
function setListByForm(row: any) {
  if (row) {
    examClinicCheckList.value = []
    if (examTypeList.value) {
      positionTypeArr.value = dictDataMap.value['position_type']
      examTypeList.value.forEach((examType: any) => {
        examType.examVsClinicVoList.forEach((item: any) => {
          row.forEach((clinicCheck: any) => {
            if (clinicCheck.vsId === item.vsId) {
              examClinicCheckList.value.push(item.vsId)
              const examPositionArray = clinicCheck.examPositionArray;
              item.examPositionArray = []
              examPositionArray.forEach((examPosition: any) => {
                item.examPositionArray.push(examPosition.dictValue)
              })
            }
          })
        })
      })
    }
  }
  console.log("examTypeList",examTypeList.value)
}


defineExpose({saveExamDialog, emptySearchInput, emptyExamTypeList, setListByForm, getListExamTypeFun});
</script>
<script lang="ts">
export default {
  name: "ItemSelectDialog",
};
</script>

<style scoped>
.clinic-div {
  color: #000000;
}

.exam-type-div {
  color: #ff9100;
}

.exam-lab-check {
  width: 300px;
  height: 100px;
  border: 1px dashed #ababab;
  border-radius: 10px;
  padding-left: 5px;
}

.exam-lab-check-div {
  width: 200px;
  word-wrap: break-word;
  white-space: break-spaces;
}

.exam-lab-type-div {
  right: 5px;
  bottom: 22px;
  position: absolute;
  float: right;
}

:deep(.el-tag + .el-tag) {
  margin-left: 0px;
}

:deep(.el-checkbox) {
  white-space: normal;
}

:deep(.el-tag--small .el-tag__close) {
  display: none;
}

:deep(.el-select__selection .el-tag .el-tag__content) {
  margin-right: 5px;
}

:deep(.el-select--small .el-select__selection.is-near) {
  height: 45px;
  overflow-y: auto;
}

</style>
